package com.hbyj.object;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.hbyj.db.function.DbTools;
import com.hbyj.hbm.vo.Functions;
import com.hbyj.hbm.vo.RoleFunction;
import com.hbyj.hbm.vo.Roles;

public class RoleAddData {
	private String roleName;
	private RoleWithFunction[] roleWithFunctions;
	
	public RoleAddData(){
		
	}
	
	public void updateRoleRelation(){
		Roles roles=(Roles)DbTools.findByProperty("Roles", "name", this.roleName).get(0);
		roles.setName(this.roleName);
		DbTools.saveOrUpdateObj(roles);
		//Set<RoleFunction> set = new HashSet<RoleFunction>(0);
		//roles.getRoleFunctions().clear();
		String deleteRoleFunctionHQL = "delete from RoleFunction rolefun where roles.id="+roles.getId();
		DbTools.delete(deleteRoleFunctionHQL);
		if(this.roleWithFunctions !=null){
		    for (RoleWithFunction roleWithFunction : this.roleWithFunctions) {
		    	List<Functions> functionsObj = (List<Functions>)DbTools.findByProperty("Functions", "id", roleWithFunction.getFunctionId());
				RoleFunction roleFunction = new RoleFunction(
						roleWithFunction.getFunctionId(),roles,functionsObj.get(0),roleWithFunction.getC(),roleWithFunction.getU(),roleWithFunction.getR(),
						roleWithFunction.getD(),null);
				roleFunction.setRoles(roles);
				DbTools.saveObj(roleFunction);
				//set.add(roleFunction);
				//roles.getRoleFunctions().add(roleFunction);
			}
		}
		//roles.setRoleFunctions(null);
	}
	
	public void saveRoleRelation(){
		Roles roleObj=saveRoleObj();
		if(roleObj!=null)
			saveRoleFunctions(roleObj);
	}
	
	private Roles saveRoleObj(){
		Roles roleObj = new Roles(0,this.roleName);
		Boolean rlt=DbTools.saveObj(roleObj);
		if(rlt)
			return roleObj;
		return null;
	}
	
	@SuppressWarnings("unchecked")
	private void saveRoleFunctions(Roles roleObj){
		if(this.roleWithFunctions !=null){
	    for (RoleWithFunction roleWithFunction : this.roleWithFunctions) {
	    	List<Functions> functionsObj = (List<Functions>)DbTools.findByProperty("Functions", "id", roleWithFunction.getFunctionId());
			RoleFunction roleFunction = new RoleFunction(
					0,roleObj,functionsObj.get(0),roleWithFunction.getC(),roleWithFunction.getU(),roleWithFunction.getR(),
					roleWithFunction.getD(),null);
			DbTools.saveObj(roleFunction);
		}
		}
	}

	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	public String getRoleName() {
		return roleName;
	}

	public void setRoleWithFunctions(RoleWithFunction[] roleWithFunctions) {
		this.roleWithFunctions = roleWithFunctions;
	}

	public RoleWithFunction[] getRoleWithFunctions() {
		return roleWithFunctions;
	}
}
